<script setup>
import { reactive, toRefs, ref, onMounted, nextTick } from 'vue';
import { ElDialog, ElEmpty, ElForm, ElFormItem, ElInput, ElTag, ElTree } from 'element-plus';
import { OPERATION_TYPE } from '@/common/js/common-const';
import { useSystemStore } from '@/stores';

const props = defineProps({
  roleData: {
    type: Object,
    default: () => ({}),
  },
  roleType: {
    type: String,
    default: '',
  },
  roleShow: {
    type: Boolean,
  },
});
const { roleShow, roleType, roleData } = toRefs(props);
const emit = defineEmits(['handleRoleShowEmit', 'handleRoleParamEmit']);
const systemStore = useSystemStore();

const defaultProps = {
  children: 'children',
  label: 'title',
};

const treeRef = ref(null);
const formRef = ref(null);
const dataTree = ref([]);
const defaultChecked = ref([]);

const formInline = reactive({
  title: '',
  permissionIds: [],
  description: '',
});

const rules = {
  title: [
    {
      required: true,
      message: '此项为必填项',
      trigger: 'blur',
    },
  ],
};

const closeBoxShowDialog = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  emit('handleRoleShowEmit', false);
};

onMounted(() => {
  dataTree.value = systemStore.systemMenu;

  if (roleType.value == OPERATION_TYPE.ADD) {
    if (!formRef.value) return;
    formRef.value.resetFields();
  }

  if (Object.keys(roleData.value).length) {
    formInline.title = roleData.value.title;
    formInline.description = roleData.value.description;

    if (roleType.value == OPERATION_TYPE.EDIT) {
      formInline.permissionIds = roleData.value.permissions?.map((item) => {
        return item.id;
      });

      defaultChecked.value = formInline?.permissionIds || [];
      nextTick(() => {
        defaultChecked.value.reverse().map((i) => {
          treeRef.value.setChecked(i, true, false); // 选中树
        });
      });
    }
  }
});

const handleCheckChange = (nodeObj, SelectedObj) => {
  formInline.permissionIds = [...SelectedObj.halfCheckedKeys, ...SelectedObj.checkedKeys];
};

const handleSubmit = () => {
  formRef.value.validate((err) => {
    if (err) {
      if (roleType.value == OPERATION_TYPE.ADD) {
        emit('handleRoleParamEmit', formInline, OPERATION_TYPE.ADD);
      }

      if (roleType.value == OPERATION_TYPE.EDIT) {
        formInline['id'] = roleData.value.id;
        formInline.permissionIds = formInline.permissionIds?.length ? formInline.permissionIds : null;
        emit('handleRoleParamEmit', formInline, OPERATION_TYPE.EDIT);
      }
    }
  });
};
</script>
<template>
  <div class="menu-loading">
    <ElDialog
      v-if="roleShow"
      v-model="roleShow"
      align-center="center"
      :append-to-body="false"
      :title="roleType == OPERATION_TYPE.EDIT ? '编辑' : roleType == OPERATION_TYPE.ADD ? '新建' : '查看'"
      :close-on-click-modal="false"
      destroy-on-close
      draggable
      @close="closeBoxShowDialog()"
    >
      <main>
        <ElForm ref="formRef" :rules="rules" :model="formInline" label-position="top">
          <ElFormItem label="角色名称" prop="title">
            <ElInput v-model.trim="formInline.title" show-word-limit maxlength="50" type="text" />
          </ElFormItem>
          <ElFormItem label="数据权限">
            <div class="border-box p-10px">
              <ElTree
                v-if="dataTree?.length && roleType !== OPERATION_TYPE.LOOK"
                ref="treeRef"
                style="max-width: 600px"
                :data="dataTree"
                show-checkbox
                node-key="id"
                :props="defaultProps"
                :check-strictly="false"
                @check="handleCheckChange"
              />
              <ElEmpty
                v-if="
                  (!dataTree?.length && roleType !== OPERATION_TYPE.LOOK) ||
                  (!roleData.permissions?.length && roleType == OPERATION_TYPE.LOOK)
                "
                description="暂无数据"
              />

              <div v-if="roleType === OPERATION_TYPE.LOOK">
                <ElTag v-for="item in roleData.permissions" :key="item.id" size="large" type="warning">{{
                  item?.title
                }}</ElTag>
              </div>
            </div>
          </ElFormItem>
          <ElFormItem label="角色描述">
            <ElInput v-model.trim="formInline.description" maxlength="50" type="text" />
          </ElFormItem>
        </ElForm>
      </main>
      <div v-if="roleType !== OPERATION_TYPE.LOOK" class="dialog-footer">
        <div @click="closeBoxShowDialog()">取消</div>
        <div @click="handleSubmit()">保存</div>
      </div>
    </ElDialog>
  </div>
</template>

<style scoped lang="scss">
.menu-loading {
  :deep(.el-dialog) {
    width: 700px;
    border-radius: 6px;
  }

  main {
    .border-box {
      width: 100%;
      min-height: 300px;
      max-height: 300px;
      overflow: auto;
      border: 1px solid $border-color;
      border-radius: 6px;
      &::-webkit-scrollbar {
        display: none;
        width: 0 !important;
      }
    }
  }

  .dialog-footer {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 30px;
    text-align: right;
    div {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100px;
      height: 40px;
      font-size: 16px;
      border-radius: 4px;
      cursor: pointer;

      &:first-child {
        color: $base-color-info;
        border: 1px solid #e9e9e9;
      }

      &:nth-child(2) {
        margin: 0 20px;
        color: $base-button-color-white;
        background-color: $base-button-color-add;
      }
    }
  }
}
</style>
